<template>
  <div class="transactions-management">
    <el-card class="main-card">
      <!-- 页面头部 -->
      <TransactionHeader 
        :stats="stats"
        :loading="loading"
        :capturing="capturing"
        :selected-transactions="selectedTransactions"
        :view-mode="viewMode"
        :show-advanced-filter="showAdvancedFilter"
        @search="handleSearch"
        @reset="handleReset"
        @toggle-filter="showAdvancedFilter = !showAdvancedFilter"
        @view-mode-change="viewMode = $event"
        @showImportWizard="showImportDialog = true"
        @smart-filter="showFilterDialog = true"
        @show-batch-operations="showBatchDialog = true"
        @load-transactions="loadTransactions"
        @export-transactions="handleExportTransactions"
        @handle-smart-capture="handleSmartCapture"
      />
      
      <!-- 高级筛选 -->
      <TransactionFilter 
        v-show="showAdvancedFilter"
        v-model="queryParams"
        @search="handleSearch"
        @reset="handleReset"
      />
      
      <!-- 智能建议 -->
      <SmartActions 
        v-if="showSmartActions"
        :smart-suggestions="smartSuggestions"
        :get-suggestion-type="getSuggestionType"
        @apply-suggestion="applySuggestion"
        @apply-all-suggestions="applyAllSuggestions"
        @remove-suggestion="removeSuggestion"
      />
      
      <!-- 智能提醒 -->
      <TransactionSmartAlerts 
        :transactions="tableData"
        @alert-click="handleAlertClick"
      />
      
      <!-- 交易表格 -->
      <TransactionTable
        ref="transactionTableRef"
        v-model:query-params="queryParams"
        :table-data="tableData"
        :loading="loading"
        :pagination="{ page: queryParams.page, limit: queryParams.limit, total: total }"
        :selected-transactions="selectedTransactions"
        :show-advanced-filter="showAdvancedFilter"
        @selection-change="handleSelectionChange"
        @view-detail="handleViewTransactionDetail"
        @manual-match="handleManualMatch"
        @edit="handleEditTransactionRemark"
        @refresh="loadTransactions"
      />
      
      <!-- 分页 -->
      <TransactionPagination
        :model-value="{ page: queryParams.page, limit: queryParams.limit }"
        :total="total"
        @update:model-value="(val: { page: number; limit: number }) => { queryParams.page = val.page; queryParams.limit = val.limit }"
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
      />
    </el-card>
    
    <!-- 导入向导对话框 -->
    <TransactionImportWizard 
      v-model="showImportDialog" 
      @import-success="handleImportSuccess"
    />
    
    <!-- 智能过滤设置抽屉 -->
    <SmartFilter 
      v-model="showFilterDialog" 
      @rules-updated="handleFilterRulesUpdated"
    />
    
    <!-- 批量操作面板 -->
    <BatchOperationPanel 
      v-model="showBatchDialog" 
      :selected-transactions="selectedTransactions"
      @batch-action="handleBatchAction"
    />
    
    <!-- 流水详情对话框 -->
    <TransactionDetail
      v-model="showTransactionDetailDialog"
      :transaction="currentTransaction"
      @edit="handleEditTransactionRemark"
    />
    
    <!-- 手动匹配抽屉 -->
    <ManualMatchDialog
      v-model="showManualMatchDialog"
      :transaction="currentTransaction"
      @match-success="handleMatchSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from '@vue/runtime-core'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Money, Clock, Checked, Filter, Upload, MagicStick, Operation, 
  Download, Refresh, Search, Sort, Setting, View, 
  Connection, Edit, More, CopyDocument, Delete, CircleCheck,
  OfficeBuilding, QuestionFilled, Check, SetUp, Star, InfoFilled
} from '@element-plus/icons-vue'
import { useAppStore } from '@/stores/appStore'
import StatCard from '@/components/StatCard.vue'

// 导入API函数
import { getTransactions } from '@/api/transaction'

// 导入拆分的组件
import TransactionFilter from './components/TransactionFilter.vue'
import TransactionTable from './components/TransactionTable.vue'
import TransactionCard from './components/TransactionCard.vue'
import SmartActions from './components/SmartActions.vue'
import TransactionPagination from './components/TransactionPagination.vue'

// 导入新创建的组件
import ImportWizard from './components/ImportWizard.vue'
import TransactionImportWizard from './components/TransactionImportWizard.vue'
import SmartFilter from './components/SmartFilter.vue'
import BatchOperationPanel from './components/BatchOperationPanel.vue'
import TransactionHeader from './components/TransactionHeader.vue'
import TransactionView from './components/TransactionView.vue'
import TransactionDetail from './components/TransactionDetail.vue'
import ManualMatchDialog from './components/ManualMatchDialog.vue'
import TransactionSmartAlerts from './components/TransactionSmartAlerts.vue'

// Store 和 Router
const appStore = useAppStore()
const router = useRouter()

// 响应式数据
const transactionTableRef = ref()
const loading = ref(false)
const capturing = ref(false)

const selectedTransactions = ref<any[]>([])
const tableData = ref<any[]>([])
const total = ref(0)

const showAdvancedFilter = ref(false)
const viewMode = ref<'table' | 'card'>('table')
const smartSuggestions = ref<any[]>([])
const filterRules = ref<any[]>([])

const currentTransactionId = ref('')
const currentTransaction = ref<any>(null)
const showTransactionDetailDialog = ref(false)
const showManualMatchDialog = ref(false) // 新增手动匹配对话框状态

// 对话框显示状态
const showImportDialog = ref(false)
const showFilterDialog = ref(false)
const showBatchDialog = ref(false)

// 监听 showImportDialog 的变化
watch(showImportDialog, (newVal) => {
  console.log('showImportDialog changed to:', newVal)
})

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 20,
  transactionStatus: '',
  payerName: '',
  transactionDateRange: [],
  minAmount: undefined,
  maxAmount: undefined,
  dataSource: '',
  bankName: '',
  transactionType: '',
  importBatch: '',
  hasRemark: false,
  showDuplicates: false,
  sortField: 'transaction_date',
  sortOrder: 'desc'
})

// 统计信息
const stats = reactive({
  totalTransactions: 1280,
  unmatchedTransactions: 240,
  matchedTransactions: 960,
  filteredTransactions: 80,
  todayTransactions: 25,
  monthlyAmount: 1285000,
  autoMatchRate: 85,
  dataQualityScore: 92,
  todayTrend: 12,
  amountTrend: 5,
  matchTrend: 3,
  qualityTrend: -2
})

// 计算属性
const showSmartActions = computed(() => smartSuggestions.value.length > 0)

// 方法
const loadTransactions = async () => {
  loading.value = true
  try {
    // 使用真实的API获取数据
    const response = await getTransactions({
      page: queryParams.page,
      limit: queryParams.limit,
      transactionStatus: queryParams.transactionStatus,
      payerName: queryParams.payerName,
      startDate: queryParams.transactionDateRange?.[0],
      endDate: queryParams.transactionDateRange?.[1],
      minAmount: queryParams.minAmount,
      maxAmount: queryParams.maxAmount,
      dataSource: queryParams.dataSource,
      bankName: queryParams.bankName,
      transactionType: queryParams.transactionType,
      importBatch: queryParams.importBatch,
      hasRemark: queryParams.hasRemark,
      showDuplicates: queryParams.showDuplicates,
      sortField: queryParams.sortField,
      sortOrder: queryParams.sortOrder
    })
    
    if (response.success) {
      tableData.value = response.data.items || response.data.rows || []
      total.value = response.data.total || 0
      
      // 更新统计信息
      stats.totalTransactions = total.value
      // 其他统计信息可以根据需要从后端获取或计算
      
      // 加载智能建议
      loadSmartSuggestions()
    } else {
      ElMessage.error(response.message || '加载流水数据失败')
    }
  } catch (error) {
    ElMessage.error('加载流水数据失败')
  } finally {
    loading.value = false
  }
}

const loadSmartSuggestions = async () => {
  // 模拟加载智能建议
  smartSuggestions.value = [
    {
      id: '1',
      type: 'filter',
      description: '建议过滤5条非业务相关流水',
      transactions: ['1', '2', '3', '4', '5'],
      confidence: 95
    },
    {
      id: '2',
      type: 'match',
      description: '建议匹配3条高置信度流水',
      transactions: ['6', '7', '8'],
      confidence: 88
    }
  ]
}

// 获取建议类型的方法
const getSuggestionType = (type: string) => {
  const typeMap: Record<string, string> = {
    filter: 'warning',
    match: 'success',
    duplicate: 'info'
  }
  return typeMap[type] || 'info'
}

// 应用所有建议
const applyAllSuggestions = () => {
  ElMessageBox.confirm('确定要应用所有智能建议吗？', '应用所有建议', {
    type: 'warning'
    }).then(() => {
    // 应用所有建议的逻辑
    ElMessage.success('所有建议已应用')
    // 重新加载数据
    loadTransactions()
  }).catch(() => {
    // 取消应用
  })
}

// 移除建议
const removeSuggestion = (suggestionId: string) => {
  smartSuggestions.value = smartSuggestions.value.filter((s: any) => s.id !== suggestionId)
}

const handleSearch = () => {
  queryParams.page = 1
  loadTransactions()
}

const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    limit: 20,
    transactionStatus: '',
    payerName: '',
    transactionDateRange: [],
    minAmount: undefined,
    maxAmount: undefined,
    dataSource: '',
    bankName: '',
    transactionType: '',
    importBatch: '',
    hasRemark: false,
    showDuplicates: false,
    sortField: 'transaction_date',
    sortOrder: 'desc'
  })
  loadTransactions()
}

const handleSelectionChange = (selection: any[]) => {
  selectedTransactions.value = selection
}

const handleRowClick = (row: any) => {
  // 可以显示快速详情
  console.log('点击流水:', row)
}

const handlePageChange = (page: number) => {
  queryParams.page = page
  loadTransactions()
}

const handlePageSizeChange = (size: number) => {
  queryParams.limit = size
  queryParams.page = 1
  loadTransactions()
}

const applySuggestion = (suggestion: any) => {
  ElMessageBox.confirm(`确定要应用建议"${suggestion.description}"吗？`, '应用建议', {
    type: 'warning'
  }).then(() => {
    // 应用建议的逻辑
    ElMessage.success('建议已应用')
    // 重新加载数据
    loadTransactions()
  }).catch(() => {
    // 取消应用
  })

}

const handleViewTransactionDetail = (transaction: any) => {
  currentTransaction.value = transaction
  showTransactionDetailDialog.value = true
}

const handleEditTransactionRemark = (transaction: any) => {
  // 编辑备注的逻辑
  ElMessage.success('备注已更新')
}

const handleManualMatch = (transaction: any) => {
  currentTransaction.value = transaction
  showManualMatchDialog.value = true
}

const handleMatchSuccess = (transaction: any, order: any) => {
  ElMessage.success(`流水${transaction.transactionId}已成功匹配订单${order.orderId}`)
  // 重新加载数据
  loadTransactions()
}

const handleImportSuccess = () => {
  ElMessage.success('导入成功')
  // 重新加载数据
  loadTransactions()
}

const handleFilterRulesUpdated = (rules: any[]) => {
  filterRules.value = rules
  ElMessage.success('过滤规则已更新')
  // 重新加载数据
  loadTransactions()
}

const handleBatchAction = (action: string, data: any) => {
  ElMessage.success(`批量操作"${action}"执行成功`)
  // 重新加载数据
  loadTransactions()
}

// 添加处理提醒点击的方法
const handleAlertClick = (alert: any) => {
  ElMessage.info(`处理提醒: ${alert.title}`)
  // 可以根据提醒类型执行不同的操作
  switch (alert.type) {
    case 'duplicate':
      // 筛选显示重复交易
      queryParams.showDuplicates = true
      handleSearch()
      break
    case 'largeAmount':
      // 可以跳转到大额交易筛选
      ElMessage.info('已筛选显示大额交易')
      break
    case 'abnormalTime':
      // 可以跳转到异常时间交易筛选
      ElMessage.info('已筛选显示异常时间交易')
      break
  }
}

const handleExportTransactions = () => {
  // 导出流水的逻辑
  ElMessage.success('流水已导出')
}

const handleSmartCapture = () => {
  capturing.value = true
  // 智能抓取的逻辑
  setTimeout(() => {
    capturing.value = false
    ElMessage.success('智能抓取完成')
    // 重新加载数据
    loadTransactions()
  }, 2000)
}

// 生命周期
onMounted(() => {
  loadTransactions()
})
</script>

<style scoped lang="scss">
.transactions-management {
  .main-card {
    margin-bottom: 20px;
  }
}
</style>
